from django.contrib.auth import get_user_model
from rest_framework import serializers
from typing import List, Tuple, Union


from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.tokens import RefreshToken, T, AuthUser

from task.models import Group


class DynamicFieldsModelSerializer(serializers.ModelSerializer):

    def __init__(self, *args, **kwargs):

        fields: Union[List[str], Tuple[str, ...]] = kwargs.pop('fields', [])

        excludes: Union[List[str], Tuple[str, ...]] = kwargs.pop('excludes', [])

        assert not(fields and excludes), "fields 和 exculdes 是互斥的、不允许同时存在"

        super().__init__(*args,**kwargs)

        if fields:
            allowed = set(fields)
            existing = set(self.fields)
            for field_name in existing - allowed:
                self.fields.pop(field_name)

        if excludes:
            for field_name in excludes:
                self.fields.pop(field_name)


class MyRefreshToken(RefreshToken):

    @classmethod
    def for_user(cls: type[T], user: AuthUser) -> T:

        token = super().for_user(user)
        token['is_staff'] = user.is_staff
        token['username'] = user.username

        token['name'] = user.name

        if user.clazz:
            token['className'] = user.clazz.name
        else:
            token['className'] = "无"

        if user.is_superuser:
            token["roleName"] = "超级管理员"
        elif user.role:
            token["roleName"] = user.role.name
        else:
            token["roleName"] = "普通用户"

        if user.tel:
            token['tel'] = user.tel[:3] + "****" + user.tel[-4:]
        else:
            token['tel'] = "无"
        # ...

        return token



class GroupSerializer(serializers.ModelSerializer):
    num = serializers.SerializerMethodField()

    class Meta:
        model = Group
        fields = ['id', 'name', 'create_time', 'num']

    def get_num(self, obj):
        return obj.users.count()

User = get_user_model()

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username']



